package com.weishuang.monitor.leader.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishuang.monitor.leader.commons.utils.FormatUtil;
import com.weishuang.monitor.leader.entity.ServerProcessInfo;
import com.weishuang.monitor.leader.entity.vo.ServerProcessInfoVo;
import com.weishuang.monitor.leader.mapper.ServerProcessInfoMapper;
import com.weishuang.monitor.leader.service.IServerProcessInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weishuang
 * @since 2021-04-19
 */
@Service
public class ServerProcessInfoServiceImpl extends ServiceImpl<ServerProcessInfoMapper, ServerProcessInfo> implements IServerProcessInfoService {

    /**
     * 服务进程列表
     * @param sysId
     * @param serverProcessInfos
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void upServerProcessInfos(String sysId, List<ServerProcessInfo> serverProcessInfos) {
        serverProcessInfos.forEach(serverProcessInfo -> {
            serverProcessInfo.setSysId(sysId);
        });
        //删除服务所有进程
        LambdaQueryWrapper<ServerProcessInfo> eq = Wrappers.lambdaQuery(ServerProcessInfo.class).eq(ServerProcessInfo::getSysId, sysId);
        baseMapper.delete(eq);
        //插入所有服务进程
        saveBatch(serverProcessInfos);
    }

    @Override
    public List<ServerProcessInfoVo> listProcessInfos(String sysId) {
        LambdaQueryWrapper<ServerProcessInfo> serverProcessInfoLambdaQueryWrapper = Wrappers.lambdaQuery(ServerProcessInfo.class).eq(ServerProcessInfo::getSysId, sysId).orderByDesc(ServerProcessInfo::getProcessCpuLoadCumulative);
        List<ServerProcessInfo> list = baseMapper.selectList(serverProcessInfoLambdaQueryWrapper);
        List<ServerProcessInfoVo> reslut = new ArrayList<>();
        for (ServerProcessInfo serverProcessInfo : list) {
            ServerProcessInfoVo serverProcessInfoVo = BeanUtil.copyProperties(serverProcessInfo, ServerProcessInfoVo.class, "bytesWritten", "bytesRead", "residentSetSize");
            serverProcessInfoVo.setResidentSetSize(FormatUtil.formatBytes(serverProcessInfo.getResidentSetSize()));
            serverProcessInfoVo.setBytesRead(FormatUtil.formatBytes(serverProcessInfo.getBytesRead()));
            serverProcessInfoVo.setBytesWritten(FormatUtil.formatBytes(serverProcessInfo.getBytesWritten()));
            reslut.add(serverProcessInfoVo);
        }
        return reslut;
    }
}
